package com.gpframework.common;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RSAUtils {

    public static void main(String[] args) {
        //私钥
        String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJJmuK8FdbI7qZgL3SmQOJaa0rixiEolP+72lC5aSGTl7jhV9NkEjcDR4f2Kr+XBcbiiV523XbP7X9jn3LbGZ/pxjPqlJqY859QkgFtoVzRAT1k1zRFwqvupkogupbR7a1TUX/fcrUGbpcLvO8DFr9bApKyRupT7uBH11EMIZ85TAgMBAAECgYADDIwGUe0W40kC1CU5tnm41T+g17DldNIlWWuFOmpTw6AklATpHvNCBuNkguaeUkGNw7/JMDNafYulxx2gwHZ6ewg37ZZsCDOV1ZP6ChD9a1LEMvZqOVpt2sJ/nIalgGTEwMjcQhVsEtMC1uAeZzH5bPCCYnM3PelJe8+fcE4NsQJBAMQKk0NXc7/ZDF6hx+7Ku7h1qt1n2+PoFM8aBrWL2HscVGzabvB5KZG48vA00+rzRy7UIFDHh+ZhEDdc32mwmgMCQQC/LXv+ZLdLhR+rkk+lK2lV+x5jTwX9n+ujZK+lR3f8qCPOPtXtJR2s9GWPBjw6HWTXR7f7QJIrp27sOsxPffFxAkANVQ7I0KS9klxF/0iik8UKeW4iWpLYwArSPtnf9N/HF5kiQgSzc/oAwAw9i8oxu1PG+oQsGjXC1C0PJtDG1kzTAkEAjEq3jCair8PASuqykbW6tgLy+NN7xPP/Osdfcf1xWrKUm/xWhpFPJqWuhXeA6PC7GJQjujhXS7ux1Z8MYWU9sQJAKM/zuGzTxkgqyhZOW049wNpycPcqAEBdcfvi7j7TQHyICIfgY4DQr+pYz1/TWaU49sOR1g4p1zuGmWl6XCj/Tw==";
        //公钥
        String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSZrivBXWyO6mYC90pkDiWmtK4sYhKJT/u9pQuWkhk5e44VfTZBI3A0eH9iq/lwXG4oledt12z+1/Y59y2xmf6cYz6pSamPOfUJIBbaFc0QE9ZNc0RcKr7qZKILqW0e2tU1F/33K1Bm6XC7zvAxa/WwKSskbqU+7gR9dRDCGfOUwIDAQAB";
        //原文
        String str = "{\"name\":\"张三\",\"phone\":\"13800138000\",\"workNumber\":\"001\"}";

        //加密后
        String encryption = encryption(str, PUBLIC_KEY);
        log.info("原文：" + str);
        //密文
        log.info("密文：" + encryption);
        //解密后
        String decryption = decryption(encryption, PRIVATE_KEY);
        log.info("解密：" + decryption);
    }

    /**
     * 加密
     *
     * @return
     */
    public static String encryption(String content, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(content, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        char[] chars = HexUtil.encodeHex(encrypt);
        return new String(chars);
    }

    /**
     * 解密
     *
     * @return
     */
    public static String decryption(String content, String privateKey) {
        byte[] aByte = HexUtil.decodeHex(content);
        return decryption(aByte, privateKey);
    }

    /**
     * 解密
     *
     * @return
     */
    public static String decryption(byte[] content, String privateKey) {
        RSA rsa = new RSA(privateKey, null);
        return new String(rsa.decrypt(content, KeyType.PrivateKey));
    }
}
